package com.cloud.apis.organization.service.impl;

import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.core.model.Dict;
import com.cloud.apis.core.model.Organization;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.dict.db.dao.DictMapper;
import com.cloud.apis.dict.service.IDictService;
import com.cloud.apis.organization.db.dao.OrganizationMapper;
import com.cloud.apis.organization.db.dao.PostMapper;
import com.cloud.apis.organization.pojo.form.AddOrganizationForm;
import com.cloud.apis.organization.pojo.form.UpdateOrganizationForm;
import com.cloud.apis.organization.pojo.vo.GroupOrganizationVo;
import com.cloud.apis.organization.pojo.vo.OrganizationInfoVo;
import com.cloud.apis.organization.pojo.vo.OrganizationTreeVo;
import com.cloud.apis.organization.service.IOrganizationService;
import com.cloud.apis.user.db.dao.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 组织架构API相关接口业务层实现类
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/3/25
 */
@Slf4j
@Service
public class OrganizationService implements IOrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IDictService dictService;

    public OrganizationService() {
        log.info("【OrganizationService】");
    }
    @Override
    public ArrayList<Organization> getOrganizationByType(String type) {
        Dict dict =dictService.getDictByAbbreviation(type);
        if (dict==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "字典不存在");
        }
        return organizationMapper.selectOrganizationByTypeId(dict.getId());
    }

    @Override
    public ArrayList<Organization> getOrganizationByParentId(Long id) {
        if(organizationMapper.selectOrganizationById(id)==null && id!=0L){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织架构不存在");
        }
        return organizationMapper.selectOrganizationByParentId(id);
    }

    @Override
    public ArrayList<OrganizationTreeVo> getOrganizationStruct() {
        ArrayList<OrganizationTreeVo> organizationTreeVos = new ArrayList<>();
        ArrayList<Organization> organizations = organizationMapper.getOrganizationList();
        Map<Long,Organization> all = transformListToMap(organizations);
        for(Long key:all.keySet()){
            Organization mapItem = all.get(key);
            if (mapItem.getParentId()==0L){
                OrganizationTreeVo organizationTreeVo = convertListItemToTreeItem(mapItem);
                organizationTreeVos.add(organizationTreeVo);
                fillChildren(mapItem,organizationTreeVo,all);
            }
        }
        return organizationTreeVos;
    }

    private void fillChildren(Organization mapItem, OrganizationTreeVo organizationTreeVo, Map<Long, Organization> all) {
        if(mapItem.getIsEnable()){
            organizationTreeVo.setChildren(new ArrayList<>());
            Set<Long> keySet = all.keySet();
            for (Long key:keySet){
                Organization item = all.get(key);
                if(item.getParentId().equals(mapItem.getId())){
                    OrganizationTreeVo child = convertListItemToTreeItem(item);
                    organizationTreeVo.getChildren().add(child);
                    if (item.getIsEnable()){
                        fillChildren(item,child,all);
                    }
                }
            }
        }
    }

    private Map<Long, Organization> transformListToMap(List<Organization> organizationList) {
        Map<Long, Organization> organizationMap = new LinkedHashMap<>();
        for (Organization o : organizationList) {
            if (!o.getIsEnable()) {
                continue;
            }
            organizationMap.put(o.getId(),o);
        }
        return organizationMap;
    }
    private OrganizationTreeVo convertListItemToTreeItem(Organization listItem) {
        return new OrganizationTreeVo()
                .setValue(listItem.getId())
                .setLabel(listItem.getName());
    }

    private OrganizationTreeVo findDepartmentByValue(OrganizationTreeVo department, Long targetValue) {
        if (department.getValue().equals(targetValue)) {
            return department;
        }
        for (OrganizationTreeVo child : department.getChildren()) {
            OrganizationTreeVo result = findDepartmentByValue(child, targetValue);
            if (result != null) {
                return result;
            }
        }
        return null;
    }

    @Override
    public OrganizationTreeVo getAllOrganizationTree() {
        return getOrganizationStruct().get(0);
    }

    @Override
    public OrganizationTreeVo getOrganizationTreeById(Long id) {
        if (organizationMapper.selectOrganizationById(id) == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织架构不存在");
        }
        return findDepartmentByValue(getAllOrganizationTree(), id);
    }

    @Override
    public OrganizationInfoVo getOrganizationById(Long id) {
        OrganizationInfoVo organizationInfoVo = organizationMapper.getOrganizationById(id);
        if (organizationInfoVo == null) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织架构不存在");
        }
        return organizationInfoVo;
    }

    @Override
    public void updateOrganization(UpdateOrganizationForm form) {
        if(form.getAbbreviation()!=null){
            OrganizationInfoVo organizationInfoVo = organizationMapper.getOrganizationByAbbreviation(form.getAbbreviation());
            if(organizationInfoVo!=null && !organizationInfoVo.getAbbreviation().equals(form.getAbbreviation())){
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织简称已存在");
            }
        }
        if(!form.getIsEnable()){
            if(userMapper.getUserByOrganizationId(form.getId()).size()>0){
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该组织下有成员，不能停用");
            }
        }
        if(organizationMapper.getOrganizationById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织架构不存在");
        }
        int i = organizationMapper.updateOrganization(form);
        if (i == 0) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "更新组织架构失败");
        }
    }

    @Override
    public OrganizationInfoVo addOrganization(AddOrganizationForm form) {
       OrganizationInfoVo organizationInfoVo = organizationMapper.getOrganizationByAbbreviation(form.getAbbreviation());
        if(organizationInfoVo!=null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织简称已存在");
        }
        if(organizationMapper.getOrganizationById(form.getParentId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "无该父级组织");
        }
        if(dictMapper.selectDictById(form.getTypeId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "无该组织类型");
        }
        int num = organizationMapper.insertOrganization(form);
        if (num == 0) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "添加组织架构失败");
        }
        return organizationMapper.getOrganizationById(form.getId());
    }

    @Override
    public void deleteOrganization(Long id) {
        if(userMapper.getUserByOrganizationId(id)==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该组织架构下有用户，无法删除");
        }
        if(organizationMapper.getOrganizationById(id)==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织架构不存在");
        }
        if (organizationMapper.selectOrganizationByParentId(id).size()!=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该组织架构下有子组织，无法删除");
        }
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        if(!postMapper.selectPostByOrganizationId(ids).isEmpty()){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该组织架构下有岗位，无法删除");
        }
        int i = organizationMapper.deleteOrganization(id);
        if (i == 0) {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "删除组织架构失败");
        }
    }

    @Override
    public ArrayList<GroupOrganizationVo> listGroupOrganization() {
        ArrayList<GroupOrganizationVo> groupOrganizationVos = new ArrayList<>();
        ArrayList<Dict> dicts = dictMapper.selectDictByType("organization");
        for (int i = 0; i < dicts.size(); i++) {
            GroupOrganizationVo groupOrganizationVo = new GroupOrganizationVo();
            groupOrganizationVo.setLabel(dicts.get(i).getName());
            groupOrganizationVo.setOptions(organizationMapper.selectOrganizationByTypeId(dicts.get(i).getId()));
            groupOrganizationVos.add(groupOrganizationVo);
        }
        return groupOrganizationVos;
    }

    @Override
    public ArrayList<OrganizationInfoVo> listExpectCurIds(Long id) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "用户不存在");
        }
        return organizationMapper.listExpectCurIds(id);
    }

    @Override
    public ArrayList<OrganizationInfoVo> getOrganizationList() {
        return organizationMapper.getOrganizationInfoList();
    }


}
